package com.tianji.promotion.service.impl;

import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_RANGE_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author root
 * @since 2023-11-23
 */
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;

    @Override
    @Async("PromotionConfig")//使用自定义的线程池异步进行
    public void asyncGenerateExchangeCode(Coupon coupon) {
        Integer totalNum = coupon.getTotalNum();//代表优惠券的发放总数量，也就是需要生成的兑换码总数量
        // 方式1: 循环兑换码总数量  循环中单个获取自增id  incr（效率不高）
        // 方式2: 先调用incrBy  得到自增id最大值  然后再循环生成兑换码
        // 1. 生成自增id  借助redis  incrby
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null){
            return;
        }
        int maxSerialNum = increment.intValue();//本地自增id 的最大值
        int begin = maxSerialNum - totalNum + 1;//自增id循环开始值

        // 2. 调用工具类生成兑换码
        List<ExchangeCode> list = new ArrayList<>();
        for (int serialNum = begin; serialNum <= maxSerialNum; serialNum++){
            String code = CodeUtil.generateCode(serialNum,coupon.getId());//参数1:自增id值，参数二为优惠券id
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setId(serialNum);//兑换码id
            exchangeCode.setCode(code);
            exchangeCode.setExchangeTargetId(coupon.getId());//优惠券id
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());// 兑换码截至时间
            list.add(exchangeCode);
        }
        // 3. 待兑换码信息保存db  exchange_code  批量保存
        this.saveBatch(list);
        // 4. 写入Redis缓存，member  couponId  score  兑换码的最大序列号
        redisTemplate.opsForZSet().add(COUPON_RANGE_KEY,coupon.getId().toString(),maxSerialNum);
    }

    @Override
    public boolean updateExchangeCodeMark(long serialNum, boolean flag) {
        String key = PromotionConstants.COUPON_CODE_MAP_KEY;
        // 修改兑换码的 自增id 对应的offset值
        Boolean aBoolean = redisTemplate.opsForValue().setBit(key,serialNum,flag);
        return aBoolean!=null && aBoolean;
    }
}
